const router = require('koa-router')()
var svgCaptcha = require('svg-captcha')
const jwt = require('jsonwebtoken')
const formidable = require('formidable');
const fs = require("fs");
const path = require('path');
const myKey = "214ii"

router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

router.get('/captcha', async (ctx, next) => {
  var captcha = svgCaptcha.create();
  //console.log(captcha)
  let img = captcha.data
  ctx.session.captcha = captcha.text;
  ctx.body = `<a href="javascript: window.location.reload();">${img}</a>`;
})
router.post('/login', async (ctx, next) => {
  console.log(ctx.request.body);
  let b = ctx.request.body
  if (b.username == 'zhangsan' && b.pwd == '12345' && b.code == ctx.session.captcha) {
    ctx.body = { "code": 200, "msg": "success" };//向前端响应，前端控制台不会显示404
  } else {
    ctx.body = { "code": 404, "msg": "fail" };
  }
})

router.post("/token", async (ctx, next) => {
  let body = JSON.parse(ctx.request.body);
  let username = body.username;
  let pwd = body.password;
  //let code = body.code
  if (username == "zhangsan" && pwd == "12345") {
    console.log(username, pwd)
    let token = jwt.sign({ username: "zhangsan", pwd: "12345" }, myKey);
    ctx.body = { token: token };//响应
    console.log(token)
  }
})

router.post('/upload', async (ctx, next) => {
  let token = ctx.req.headers.authorization;
  let result = jwt.verify(token, myKey);
  console.log(result, "111111");
  const form = formidable({
    multiples: true,
    uploadDir: path.join(__dirname, "../imgs"),
    keepExtensions: true,
  });

  form.parse(ctx.req, (err, fields, files) => {
    if (err) {
      console.log(err);
      return;
    }
  });

  //ctx.body = form
  //console.log(form)
  let imgObj = JSON.parse(ctx.request.body);
  let sql = 'insert into Images (name,size,type) values(?,?,?)';
  let name = imgObj.name;
  let size = imgObj.size;
  let type = imgObj.type;
  let resultImg = await ctx.db.EXCUTE(sql,[name,size,type]);
  ctx.body = resultImg
})

router.get('/getlist', async (ctx, next) => {
  //console.log(100)
  //let p = fs.readdirSync('./imgs')//先获取名字
  //let arr = [];
  //for (let i = 0; i < p.length; i++) {
  //  console.log(p[i])
  //  let stats = fs.statSync(`./imgs/${p[i]}`);
  //  let obj = {
  //    size: stats.size,
  //    name: p[i],
  //    type: stats.mode
  //  }
  //  //arr.push(obj);
  //}

  //ctx.body = arr
  let sql = 'select * from Images';
  let result = await ctx.db.EXCUTE(sql);
  //console.log(result);
  ctx.body = result
  
});

router.post('/upload2', async (ctx, next) => {
  let fileUser = JSON.parse(ctx.request.body);
  //console.log(fileUser);
  let sql = 'insert into userinfo (name,phone,mail,address) values(?,?,?,?)';
  let name = fileUser.name;
  let phone = fileUser.phone;
  let mail = fileUser.mail;
  let address = fileUser.address;
  //console.log(fileUser.name)
  let result = await ctx.db.EXCUTE(sql,[name,phone,mail,address])
  ctx.body = result
})

router.post('/upload3', async (ctx, next) => {
  let fileLine = JSON.parse(ctx.request.body);
  //console.log(fileLine);
  let sql = 'insert into fileLine (name,road,address,phone) values(?,?,?,?)';
  let name = fileLine.name;
  let road = fileLine.road;
  let address = fileLine.address;
  let phone = fileLine.phone;
  //console.log(fileLine.name)
  let result = await ctx.db.EXCUTE(sql,[name,road,address,phone])
  ctx.body = result
})

router.post('/deleteRow', async (ctx, next) => {
  let fileUser = JSON.parse(ctx.request.body)
  console.log(fileUser)
  //let userId = fileUser.userId;
  //console.log(userId)
  let sql = 'delete from userinfo where userId = ?'
  let result = await ctx.db.EXCUTE(sql,[fileUser])
  ctx.body = result;
})

router.post('/deleteImg', async (ctx, next) => {
  let fileUser = JSON.parse(ctx.request.body)
  console.log(fileUser)
  //let userId = fileUser.userId;
  //console.log(userId)
  let sql = 'delete from images where imageId = ?'
  let result = await ctx.db.EXCUTE(sql,[fileUser])
  ctx.body = result;
})

router.post('/deleteLine', async (ctx, next) => {
  let fileUser = JSON.parse(ctx.request.body)
  console.log(fileUser)
  //let userId = fileUser.userId;
  //console.log(userId)
  let sql = 'delete from fileline where lineId = ?'
  let result = await ctx.db.EXCUTE(sql,[fileUser])
  ctx.body = result;
})

router.get('/getUserInfo', async (ctx, next) => {
  let sql = 'select * from userInfo';
  let result = await ctx.db.EXCUTE(sql);
  //console.log(result);
  ctx.body = result
})

router.get('/getLine', async (ctx, next) => {
  let sql = 'select * from fileLine';
  let result = await ctx.db.EXCUTE(sql);
  //console.log(result);
  ctx.body = result
})
module.exports = router
